<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图册管理</title>
    <!-- element -->
    <link rel="stylesheet" href="/static/plugins/element-ui/element-ui.css">
    <!-- vue -->
    <script src="/static/plugins/vue/vue.min.js"></script>
    <script src="/static/plugins/jquery/jquery.min.js"></script> 
    <script src="/static/plugins/layer/layer.js"></script> 
    <!-- 引入组件库 element -->
    <script src="/static/plugins/element-ui/element-ui.js"></script>
    <style>

        .flex {
            display: flex;

        }
        .flex-direction {
            flex-direction: column;
        }
        .flex-sub {
            flex: 1;
        }
        .flex-wrap {
            flex-wrap: wrap;
        }
        /* .overflow-scroll::-webkit-scrollbar {
            width: 0;
        } */
        .img-border {
            border: 1px solid transparent;
        }
        .img-active {
            border: 1px solid #F56C6C;
        }

        .el-input__inner {
            height: 32px;
        }

    </style>
</head>

<body>
    <div id="el">

        <el-container style="height: 500px; border: 1px solid #eee">
            <el-aside width="120px">

                <el-menu default-active="0">
                    <el-menu-item v-for="(item, index) in categoryList" :index="index" @click="handleCurrent(item, index)">{{ item.name }}</el-menu-item>
                </el-menu>
            </el-aside>

            <el-container>
                <el-header style="text-align: left; font-size: 12px">
                    <!-- 按钮组 -->
                    <el-button-group>
                        <el-button size="small" type="primary" @click="dialogFormVisible = true">添加分类</el-button>
                        <el-button size="small" type="default" @click="dialogImageVisible = true">上传图片</el-button>
                        <!-- <el-button size="small"  type="info">移动分类</el-button> -->
                        <el-popconfirm
                                title="确定删除吗？"
                                @confirm="delImage">
                            <el-button slot="reference" size="small" type="danger">删除图片</el-button>
                        </el-popconfirm>
                    </el-button-group>
                    <el-button-group>
                        <el-button size="small" type="warning" @click="confirmImage">确认</el-button>
                    </el-button-group>
                </el-header>
                <el-main>

                    <!-- 相册列表 -->
                    <el-row class="overflow-scroll flex-sub flex align-center flex-wrap"
                            style="min-height: 1px;font-size: 0;overflow: auto;"
                            v-infinite-scroll="load"
                            infinite-scroll-disabled="disabledLoad">
                        <el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="1" v-for="(item, index) in imageList" :key="index">
                            <el-image
                                    @click="chooseImage(item, index)"
                                    class="img-border"
                                    :class="{'img-active': item.checked}"
                                    style="width: 100px; height: 100px;padding: 10px;font-size: 0;margin: 0 10px 10px 0;cursor: pointer"
                                    :src="item.path"
                                    :data-id="item.id"
                                    fit="cover"
                                    lazy="true">
                            </el-image>
                        </el-col>
                    </el-row>
                    <p style="text-align: center;" v-if="loading">加载中...</p>
                    <p style="text-align: center;" v-if="noMore">没有更多了</p>
                </el-main>
            </el-container>
        </el-container>
        <!-- 添加分类弹窗 start -->
        <el-dialog title="添加分类" :visible.sync="dialogFormVisible">
            <el-form :model="form">
                <!-- <el-form-item label="上级分类" :label-width="120">
                    <el-select v-model="form.region" placeholder="请选择活动区域">
                      <el-option label="区域一" value="shanghai"></el-option>
                      <el-option label="区域二" value="beijing"></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="分类名称" :label-width="120">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
              
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="saveCategory">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 添加分类弹窗 end -->
        <!-- 图片上传 start -->
        <el-dialog title="上传图片" :visible.sync="dialogImageVisible">
            <el-upload
                list-type="text"
                :limit="9"
                ref="upload"
                class="upload-demo"
                :auto-upload="false"
                :file-list="fileList"
                action="/admin.php/admin/upload/save/dir/images"
                multiple
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :on-exceed="handleExceed"
                :data="saveData">
                <el-button slot="trigger" size="small" type="primary">选取图片</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb，先选取图片，再上传到服务器</div>
            </el-upload>
        </el-dialog>
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <!-- 图片上传 end -->
    </div>
</body>

</html>
<script>
    function GetQueryString(name)
    {
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return unescape(r[2]); return null;
    }
    let type = GetQueryString("type");
    let input_name = GetQueryString("input_name");
    new Vue({
        el: '#el',
        data() {
            return {
                keywords: '', // 搜索关键词
                current: 0, // 当前选中的分类索引
                category_id: 0, // 当前选中分类
                categoryList: [], // 分类列表
                imageList: [], // 图片列表
                loading: true, // 图片列表加载状态
                noMore: false, // 无数据
                page: 1, // 当前页码
                dialogFormVisible: false, // 控制添加分类弹窗
                form: {
                    name: '',
                },
                dialogImageVisible: false, // 控制图片上传弹窗
                saveData: {
                    category_id: 0
                },
                dialogImageUrl: '', // 当前预览图片地址
                dialogVisible: false, // 是否显示图片预览
                fileList: [], // 待上传图片列表
                type:type||1,
                input_name:input_name
            }
        },
        computed: {
            disabledLoad () {
                return this.loading || this.noMore
            }
        },
        mounted() {
            this.getImageCategory();
        },
        methods: {
            handleSelect(e) {
                this.category_id = e.id;
                this.refreshList();
            },
            querySearch(queryString, cb) {
                var categoryList = this.categoryList;
                // var results = categoryList.filter(item => {
                //     return item.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
                // })
                var results = [];
                if (queryString) {
                    results = categoryList.filter(item => {
                        return item.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
                    })
                } else {
                    results = categoryList
                }
                // 调用 callback 返回建议列表的数据
                cb(results);
            },
            handleSuccess(response, file, fileList) {
                this.dialogImageVisible = false;
                this.fileList = []
                setTimeout(this.doSuccess, 1000);
                // this.refreshList();
            },
            doSuccess() {
                this.refreshList();
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 9 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            submitUpload() {
                this.$refs.upload.submit();
            },
            /**
             * @method 选择图片
             */
            chooseImage(item, index) {
                if (!item.checked) {
                    this.$set(item, 'checked', true);
                } else {
                    this.$set(item, 'checked', false);
                }
            },
            confirmImage(){
                var ids = [];
                var srcs = [];
                $('.img-active img').each(function () {
                    srcs.push($(this).attr('src'));
                    ids.push($(this).attr('data-id'));
                });
                try{
                    parent.upload_image_callback(ids, srcs, this.type,this.input_name);
                }catch(Error){
                    console.log('callback:',Error)
                }
                var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                parent.layer.close(index);
            },
            /**
             * @method 删除图片
             */
            delImage() {
                let that = this;
                var ids = [];
                $('.img-active img').each(function () {
                    ids.push($(this).attr('data-id'));
                });

                if (ids.length === 0) return;
                $.ajax({
                    url:"/admin.php/admin/upload/image_del",
                    type:'post',
                    data:{ids:ids},
                    success(res){
                        that.$message.success(res.msg);
                        that.refreshList();
                    }
                })
            },
            
            
            /**
             * @method 获取相册分类
             */
            getImageCategory() {
                let that = this;
                $.ajax({
                    url:"/admin.php/admin/upload/category_list",
                    type:'post',
                    data:{},
                    success(res){
                        // layer.close(index);
                        // res = JSON.parse(res);                     
                        if( res.code == 1 ){
                            that.categoryList = res.data;
                            that.category_id = that.categoryList[0].id;
                            that.saveData.category_id = that.categoryList[0].id;
                            that.refreshList();
                            
                        }else{
                            that.$message.error(res.msg);
                        }
                        console.log(res.msg);
                    }
                })
            },
            /**
             * @method 选择分类
             */
             handleCurrent(item, index) {
                this.current = index;
                this.category_id = item.id;
                this.saveData.category_id = item.id;
                this.refreshList();
            },
            /**
             * @method 添加相册分类
             */
             saveCategory() {
                let that = this;
                $.ajax({
                    url:"/admin.php/admin/upload/category_save",
                    type:'post',
                    data: that.form,
                    success(res){
                        // layer.close(index);
                        // res = JSON.parse(res);                     
                        if( res.code == 1 ){
                            that.dialogFormVisible = false;
                            that.getImageCategory();
                        }else{
                            that.$message.error(res.msg);
                        }
                    }
                })
            },
            refreshList() {
                this.page = 1;
                this.noMore = false;
                this.imageList = [];
                this.getImageList();
            },
            /**
             * @method 根据相册分类获取相册
             * @author 王正航 2022/06/10 
             */
             getImageList() {
                let that = this;
                $.ajax({
                    url:"/admin.php/admin/upload/image_list",
                    type:'post',
                    data:{category_id: that.category_id, page: that.page, list_rows: '50'},
                    success(res){                  
                        if( res.code == 1 ){
                            let list = res.data.data;
                            that.imageList = that.imageList.concat(list);
                        }else{
                            that.$message.error(res.msg);
                        }
                        that.loading = false;
                    }
                })
            },
            /**
             * @method 分页加载
             * @author 王正航 2022/06/10 
             */
            load() {
                if (this.loading) return;
                this.loading = true;
                this.page++;
                this.getImageList();
            },
        },
    })
</script>